package com.xq.utils;

import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

/**
 * 集群版连接ZK，全局自动增长ID生成工具
 * @author 卡布奇诺
 */
public class ZkIdGenerator {
    /**
     * ZK连接URL
     */
    private static final String SERVER_IP = "192.168.2.120:2181,192.168.2.120:2182,192.168.2.120:2183";

    /**
     * zk客户端对象
     */
    private static ZkClient zkClient = null;

    static {
        // 初始化zk客户端对象
        zkClient = new ZkClient(SERVER_IP,10000,10000);
    }

    /**
     * 获取下一个ID
     * @param path 节点路径
     * @return 获取ID
     */
    public static Integer nextID(String path) {
        if(!zkClient.exists(path)) {
            // 如果这个节点不存在，则创建一个持久的节点
            zkClient.create(path, new byte[0], CreateMode.PERSISTENT);
        }
        // 写入数据返回状态对象
        Stat stat = zkClient.writeDataReturnStat(path, new byte[0], -1);
        // 获取ID，ID等于zk的版本号
        int id = stat.getVersion();
        return id;
    }

    public static void main( String[] args ) {
        for (int i = 1; i <= 10; i++) {
            System.out.println(nextID("/id-gen"));
        }
        // 每次查询都会递增
        Stat stat = zkClient.writeDataReturnStat("/id-gen", new byte[0], -1);
        // 11
        System.out.println(stat.getVersion());

        stat = zkClient.writeDataReturnStat("/id-gen", new byte[0], -1);
        // 12
        System.out.println(stat.getVersion());
    }
}
